package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description
 * @Author shh
 * @Date 2025-10-15
 */
@Slf4j
@Component
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 处理超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void handleTimeoutOrder(){
        log.info("处理超时订单");
        //1.查询数据库order表，查询状态为待支付的订单
        LocalDateTime now = LocalDateTime.now().minusMinutes(15);
        List<Orders> orders = ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT, now);
        //2.如果查到了数据就说明有超时订单
        if(orders != null && orders.size() > 0){
            //3.遍历订单，调用订单取消接口，修改订单状态为取消
            for(Orders order : orders){
                //4.如果超时，就调用订单取消接口，修改订单状态为取消
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时未支付");
                order.setCancelTime(LocalDateTime.now());
                ordersMapper.update(order);
            }
        }
    }
    /**
     * 处理派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDelivery(){
        log.info("处理派送中的订单");
        //1.查询数据库的order表，条件：状态：派送中，并且下单时间小于当前时间一个小时。
        LocalDateTime now = LocalDateTime.now().minusHours(1);
        List<Orders> orders = ordersMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS, now);

        //2.如果查到是数据那说明存在一直派送的订单，需要修改订单状态Status=5（已完成）.
        if (orders != null && orders.size() > 0){
            for(Orders order : orders){
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(LocalDateTime.now());
                ordersMapper.update(order);
            }
        }
    }
}
